package com.fengye.api.job;

import com.fengye.common.constants.CommonConstant;
import com.fengye.common.domain.entity.Article;
import com.fengye.api.service.ArticleService;
import com.fengye.common.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * UpdateViewCountJob
 *
 * @author 枫叶fy
 * @description 定时任务
 * @since 2024/4/9 21:31
 */
@Slf4j
@Component
public class UpdateViewCountJob {
    @Autowired
    private ArticleService articleService;

    @Autowired
    private RedisUtils redisUtils;

    /**
     * 每10分钟执行一次，将redis中的浏览量同步到数据库中
     */
    @Scheduled(cron = "0 */10 * * * ?")
    public void updateViewCount() {
        log.info("定时任务执行了");
        // 获取redis中的浏览量
        Map<String, Object> viewCountMap = redisUtils.hGetMap(CommonConstant.ARTICLE_VIEW_COUNT_REDIS_KEY);

        // 用forEach遍历viewCountMap
       //  viewCountMap.forEach((key, value) -> {
       //      Long viewCount = Long.valueOf(value.toString());
       //      Article article = new Article();
       //      article.setId(Long.valueOf(key));
       //      article.setViewCount(viewCount);
       //
       //      // 更新到数据库
       //      LambdaUpdateWrapper<Article> updateWrapper = new LambdaUpdateWrapper<>();
       //      updateWrapper.eq(Article::getId, article.getId());
       //      articleService.update(article, updateWrapper);
       // });

        // stream流遍历viewCountMap
        List<Article> articles = viewCountMap.entrySet().stream()
                .map(entry -> {
                    Long viewCount = Long.valueOf(entry.getValue().toString());
                    Article article = new Article();
                    article.setId(Long.valueOf(entry.getKey()));
                    article.setViewCount(viewCount);
                    return article;
                }).collect(Collectors.toList());
        // 更新到数据库
        articleService.updateBatchById(articles);
    }
}
